package processor

import (
	"encoding/json"
	"fmt"
	"log"
	"net"

	"github.com/clebeg/gochat/client/manager"
	"github.com/clebeg/gochat/protocol"
	"github.com/clebeg/gochat/utils"
)

type UserProcessor struct {
	Conn net.Conn
}

// 用户登录提示输入
func getInputParams() (username int, password int, err error) {
	fmt.Printf("请输入用户名：")
	_, err = fmt.Scanf("%d\n", &username)
	if err != nil {
		err = fmt.Errorf("输入用户名有误，用户名只能是整数: %s", err)
		return
	}
	fmt.Printf("请输入密码：")
	_, err = fmt.Scanf("%d\n", &password)
	if err != nil {
		err = fmt.Errorf("输入密码有误，密码只能是整数: %s", err)
		return
	}
	fmt.Printf("您输入的账号名=%d, 密码=%d\n", username, password)
	return
}

// 用户登录想服务器传输数据
func (l *UserProcessor) DoLogin() (err error) {
	username, password, err := getInputParams()

	if err != nil {
		return
	}

	reqMsg := protocol.LoginMsgReq{
		Username: username,
		Password: password,
	}

	jsonBytes, err := json.Marshal(reqMsg)

	if err != nil {
		err = fmt.Errorf("json.Marshal(reqMsg) err, err msg=%v", err)
		return
	}

	transfer := utils.Transfer{
		Conn: l.Conn,
	}

	err = transfer.SendMsg(jsonBytes, protocol.LoginMsgType)

	if err != nil {
		return
	}

	return
}

// 用户登录想服务器传输数据
func (l *UserProcessor) DoRegister() (err error) {
	username, password, err := getInputParams()

	if err != nil {
		return
	}

	reqMsg := protocol.RegisterMsgReq{
		Username: username,
		Password: password,
	}

	jsonBytes, err := json.Marshal(reqMsg)

	if err != nil {
		err = fmt.Errorf("json.Marshal(userInfo) err, err msg=%v", err)
		return
	}

	transfer := utils.Transfer{
		Conn: l.Conn,
	}

	err = transfer.SendMsg(jsonBytes, protocol.RegisterMsgType)

	if err != nil {
		return
	}

	return
}

func ShowOnlineUsers() {
	var onlineUserIds = make([]int, 0)
	for _, up := range manager.OnlineUserProfiles {
		onlineUserIds = append(onlineUserIds, up.Username)
	}
	log.Printf("当前在线用户：%d，其他在线用户：%v\n", manager.CurLoginUser, onlineUserIds)
}
